package com.xinan.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * </p>
 * Function List:<br>
 * 常用的时间操作
 * 
 * @author 
 * @version Revision:1.0 Date: 2012-9-15 下午05:44:00
 */
public class DateUtils {
	/**
	 * 计算两个日期之间的差距天数
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
    public static final String pattern_date = "yyyy-MM-dd";
    public static final String pattern_datetime = "yyyy-MM-dd HH:mm:ss";
    public static final String pattern_datetimeMillisecond = "yyyy-MM-dd HH:mm:ss:SSS";

    /**
     * 格式化
     * @param date
     * @param pattern
     * @return
     */
    public static String format(Date date, String pattern) {
        DateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }

    public static int cutTwoDateToDay(Date a, Date b) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		int theday = 0;
		try {
			Date beginDate = format.parse(format.format(a));
			Date endDate = format.parse(format.format(b));

			calendar.setTime(beginDate);
			long begin = calendar.getTimeInMillis();
			calendar.setTime(endDate);
			long end = calendar.getTimeInMillis();

			theday = (int) ((end - begin) / (86400000));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return theday;
	}

    public static String getCurrentDate(String format)
    {
        SimpleDateFormat df = new SimpleDateFormat(format);
        return df.format(new Date());
    }

	/**
	 * 将数字型的时间转为字符串（80 -> 01:20）
	 * 
	 * @param time
	 * @return
	 */
	public static String intToTimeString(int time) {
		String hour = String.valueOf(time / 60);
		String minute = String.valueOf(time - time / 60 * 60);

		if (hour.length() < 2) {
			hour = "0" + hour;
		}
		if (minute.length() < 2) {
			minute = "0" + minute;
		}
		return hour + ":" + minute;
	}

	/**
	 * 取出两个时间出较大的时间
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public static Date MaxDate(Date a, Date b) {
		if (a.before(b)) {
			return b;
		} else {
			return a;
		}
	}

	/**
	 * 取出两个时间出较小的时间
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public static Date MinDate(Date a, Date b) {
		if (a.before(b)) {
			return a;
		} else {
			return b;
		}
	}

	/**
	 * 计算给定日期是星期几
	 * 
	 * @param date
	 * @return
	 */
	public static int getWeekOfDate(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w == 0)
			w = 7;
		return w;
	}

	/**
	 * 格式化日期
	 *
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static String formatDate(Date date, String pattern) {
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		return format.format(date);
	}

	/**
	 * 根据给定日期字符串和日期格式 创建日期
	 *
	 * @param dateString
	 * @param pattern
	 * @return
	 * @throws java.text.ParseException
	 */
	public static Date createDate(String dateString, String pattern) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat(pattern);
		return format.parse(dateString);
	}

    /**
     * 返回指定年数位移后的日期
     */
    public static Date yearOffset(Date date, int offset) {
        return offsetDate(date, Calendar.YEAR, offset);
    }

    /**
     * 返回指定月数位移后的日期
     */
    public static Date monthOffset(Date date, int offset) {
        return offsetDate(date, Calendar.MONTH, offset);
    }

    /**
     * 返回指定天数位移后的日期
     */
    public static Date dayOffset(Date date, int offset) {
        return offsetDate(date, Calendar.DATE, offset);
    }

    /**
     * 返回指定日期相应位移后的日期
     *
     * @param date
     *            参考日期
     * @param field
     *            位移单位，见 {@link java.util.Calendar}
     * @param offset
     *            位移数量，正数表示之后的时间，负数表示之前的时间
     * @return 位移后的日期
     */
    public static Date offsetDate(Date date, int field, int offset) {
        Calendar calendar = convert(date);
        calendar.add(field, offset);
        return calendar.getTime();
    }

    private static Calendar convert(Date date) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        return calendar;
    }
    public static Date parseDate(String value,Class targetType,String... formats) {
        for(String format : formats) {
            try {
                long v = new SimpleDateFormat(format).parse(value).getTime();
                return (Date)targetType.getConstructor(long.class).newInstance(v);
            }catch(ParseException e) {
            }catch(Exception e) {
                throw new RuntimeException(e);
            }
            try {
                return (Date)targetType.getConstructor(String.class).newInstance(value);
            }catch(Exception e) {
            }
        }
        throw new IllegalArgumentException("cannot parse:"+value+" for date by formats:"+ Arrays.asList(formats));
    }

    public static boolean isDateType(Class<?> targetType) {
        if(targetType == null) return false;
        return targetType == java.util.Date.class || targetType == java.sql.Timestamp.class || targetType == java.sql.Date.class || targetType == java.sql.Time.class;
    }

    /**
     * 返回两个日期之间隔了多少天，包含开始、结束时间
     * @param start
     * @param end
     * @return
     */
    public static List<String> getDaySpaceDate(Date start, Date end) {
        Calendar fromCalendar = Calendar.getInstance();
        fromCalendar.setTime(start);
        fromCalendar.set(Calendar.HOUR_OF_DAY, 0);
        fromCalendar.set(Calendar.MINUTE, 0);
        fromCalendar.set(Calendar.SECOND, 0);
        fromCalendar.set(Calendar.MILLISECOND, 0);

        Calendar toCalendar = Calendar.getInstance();
        toCalendar.setTime(end);
        toCalendar.set(Calendar.HOUR_OF_DAY, 0);
        toCalendar.set(Calendar.MINUTE, 0);
        toCalendar.set(Calendar.SECOND, 0);
        toCalendar.set(Calendar.MILLISECOND, 0);

        List<String> dateList = new LinkedList<String>();

        long dayCount = (toCalendar.getTime().getTime() - fromCalendar.getTime().getTime()) / (1000 * 60 * 60 * 24);
        if(dayCount < 0){
            return dateList;
        }

        dateList.add(format(fromCalendar.getTime(), pattern_date));

        for (int i = 0; i < dayCount; i++) {
            fromCalendar.add(Calendar.DATE, 1);// 增加一天
            dateList.add(format(fromCalendar.getTime(), pattern_date));
        }

        return dateList;
    }


    public static void main(String[] args) throws ParseException {
//		System.out.println(formatDate(new Date(), "yyyyMMdd"));
//        System.out.println(formatDate(dayOffset(new Date(),-20), "yyyyMMdd"));
//        Pattern p = Pattern.compile("/static/(.*)");
//        System.out.println(p.matcher("/wuliu/static/easyui/1.3.3/themes/default/easyui.css").matches());
        System.out.println(Integer.MAX_VALUE);
    }
}
